import java.util.ArrayList;
import java.util.List;

// 二叉树的层序遍历
// 测试链接 : https://leetcode.cn/problems/binary-tree-level-order-traversal/
public class LevelOrderTraversal {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
    }

    public static int MAX = 2001;

    public static TreeNode[] arr= new TreeNode[MAX];
    public static int l,r;

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();

        if(root == null) {
            return ret;
        }
        arr[r++] = root;
        while (l < r ) {
            int size = r - l;

            List<Integer> list = new ArrayList<>();
            for(int i = 0; i < size; ++i) {
                TreeNode node = arr[l++];
                list.add(node.val);

                if(node.left != null) {
                    arr[r++] = node.left;
                }
                if(node.right != null){
                    arr[r++] = node.right;
                }
            }
            ret.add(list);
        }
        return ret;
    }
}
